#include <cfloat>
#include <algorithm>
#include "gc.h"
#include "Path.h"

void computeComponentInsideCenter (LabelImage::Pointer labelImage, 
				   Component const& component, int& xc, int& yc, 
				   VerboseLevel verbose)
{
  double sumx = 0.0;
  double sumy = 0.0;
  for (ComponentPointSet::const_iterator itr = component.points.begin(); 
       itr != component.points.end(); itr++) {
    sumx += double(itr->x);
    sumy += double(itr->y);
  }
  xc = int(sumx / double(component.points.size()) + 0.5);
  yc = int(sumy / double(component.points.size()) + 0.5);
  LabelImage::IndexType index;
  index[0] = xc;
  index[1] = yc;
  if (labelImage->GetPixel(index) != component.no) {
    if (verbose == VERBOSE_HIGH) {
      std::cout << "XML: center not inside..." << std::endl;
    }
    double minDist2 = DBL_MAX;
    int xmin;
    int ymin;
    for (ComponentPointSet::const_iterator itr = component.points.begin(); 
	 itr != component.points.end(); itr++) {
      double dist2 = (double(xc) - itr->x) * (double(xc) - itr->x) 
	+ (double(yc) - itr->y) * (double(yc) - itr->y);
      if (dist2 < minDist2) {
	minDist2 = dist2;
	xmin = itr->x;
	ymin = itr->y;
      }
    }
    xc = xmin;
    yc = ymin;
  }
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void writeXML (Volume const& volume, Graph3D const& graph, 
	       SegmentationGraph const& resSegGraph, 
	       int startSliceNo, const char* xmlPath, 
	       VerboseLevel verbose, int pathID)
{
  TiXmlDocument doc;
  TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", "");
  doc.LinkEndChild(decl);
  TiXmlElement* root = new TiXmlElement("AllPaths");
  root->SetAttribute("num", 1);
  doc.LinkEndChild(root);
  TiXmlComment* comment = new TiXmlComment();
  comment->SetValue("List of paths for test");
  root->LinkEndChild(comment);

  Path path;
  for (SegGraphSegNodeSet::const_iterator ritr = resSegGraph.segNodeSet.begin(); 
       ritr != resSegGraph.segNodeSet.end(); ritr++) {
    int layerNo = ritr->layerNo;
    int nodeNo = ritr->nodeNo;
    int componentNo = graph.nodes[layerNo][nodeNo].componentNo;
    int xc;
    int yc;
    computeComponentInsideCenter(volume.layers[layerNo].labelImage, 
				 volume.layers[layerNo].components[componentNo], 
				 xc, yc, verbose);
    path.add(layerNo + startSliceNo, componentNo, 0.0, 0.0, xc, yc);
  }
  TiXmlElement* pathTag = new TiXmlElement("Path");
  pathTag->SetAttribute("filename", "");
  pathTag->SetAttribute("id", pathID);
  root->LinkEndChild(pathTag);
  path.writeXMLPath(pathTag);
  doc.SaveFile(xmlPath);
}
